package com.lz.ub.core

import android.os.Handler
import android.os.Looper
import android.os.Message
import com.lz.ub.UBCEventCallback
import com.lz.ub.UBCExecute
import java.lang.ref.WeakReference

/**
 * @author You
 * USB Command线程切换器 默认实现类
 */
class UBCHandler(callback: UBCEventCallback, looper: Looper) : Handler(looper), UBCExecute {

    companion object {
        private const val MSG_RESTART = 1
        private const val MSG_OK = 2
        private const val MSG_CONNECTED = 3
        private const val MSG_SUCCESS = 4
        private const val MSG_SERVICE = 5
        private const val MSG_DISCONNECTED = 6
        private const val MSG_WRITE = 7
        private const val MSG_RECEIVED = 8
        private const val MSG_RECEIVED_HEX = 9
        private const val MSG_SCANNER = 10
        private const val MSG_ERR = 11
    }

    private val reference = WeakReference(callback)

    override fun handleMessage(msg: Message) {
        when (msg.what) {
            MSG_RESTART -> reference.get()?.onRestart()
            MSG_OK -> reference.get()?.onOK()
            MSG_CONNECTED -> reference.get()?.onConnected(msg.obj as String, msg.arg1)
            MSG_SUCCESS -> reference.get()?.onSuccess()
            MSG_SERVICE -> reference.get()?.onService()
            MSG_DISCONNECTED -> reference.get()?.onDisconnected(msg.obj as String)
            MSG_WRITE -> reference.get()?.onWrite(msg.arg1)
            MSG_RECEIVED -> reference.get()?.onReceived(msg.arg1, msg.obj as String)
            MSG_RECEIVED_HEX -> reference.get()?.onReceivedHex(msg.arg1,
                msg.obj as ByteArray, msg.arg2.shr(8).and(0xFF), msg.arg2.and(0xFF))
            MSG_SCANNER -> reference.get()?.onScan(msg.obj as UBCScanResult)
            MSG_ERR -> reference.get()?.onError()
        }
    }

    override fun sendRestart() {
        sendEmptyMessage(MSG_RESTART)
    }

    override fun sendOK() {
        sendEmptyMessage(MSG_OK)
    }

    override fun sendConnected(mac: String, id: Int) {
        sendMessage(obtainMessage(MSG_CONNECTED, id, 0, mac))
    }

    override fun sendSuccess() {
        sendEmptyMessage(MSG_SUCCESS)
    }

    override fun sendService() {
        sendEmptyMessage(MSG_SERVICE)
    }

    override fun sendDisconnected(mac: String) {
        sendMessage(obtainMessage(MSG_DISCONNECTED, mac))
    }

    override fun sendWrite(size: Int) {
        sendMessage(obtainMessage(MSG_WRITE, size, 0))
    }

    override fun sendReceived(id: Int, data: String) {
        sendMessage(obtainMessage(MSG_RECEIVED, id, 0, data))
    }

    override fun sendReceivedHex(id: Int, bytes: ByteArray, start: Int, size: Int) {
        sendMessage(obtainMessage(MSG_RECEIVED_HEX, id, start.shl(8) + size, bytes))
    }

    override fun sendScan(result: UBCScanResult) {
        sendMessage(obtainMessage(MSG_SCANNER, result))
    }

    override fun sendError() {
        sendEmptyMessage(MSG_ERR)
    }
}